import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

let lifeData = {};

try {
  // 尝试获取本地是否存在lifeData变量，第一次启动APP时是不存在的
  lifeData = uni.getStorageSync('lifeData');
} catch (e) {

}

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = ['vuex_user', 'vuex_address', 'vuex_default_address', 'merchant_info', 'prev_page',"vuex_user_code"];

// 保存变量到本地存储中
const saveLifeData = function (key, value) {
  if (saveStateKeys.indexOf(key) != -1) {
    let tmp = uni.getStorageSync('lifeData');
    tmp = tmp ? tmp : {};
    tmp[key] = value;
    uni.setStorageSync('lifeData', tmp);
  }
}

const state = {
  // 用户信息
  vuex_user: lifeData.vuex_user ? lifeData.vuex_user : {},
  // 收货地址
  vuex_address: lifeData.vuex_address ? lifeData.vuex_address : { linkman: '', linktel: '', address: '' },
  //默认选择地址
  vuex_default_address: lifeData.vuex_default_address ? lifeData.vuex_default_address : {},
  // 进货订单List
  vuex_order_list: lifeData.vuex_order_list ? lifeData.vuex_order_list : [],
  // 商户申请 选择的学校信息
  vuex_school: lifeData.vuex_school ? lifeData.vuex_school : {},
  merchant_info: lifeData.merchant_info ? lifeData.merchant_info : {},
  prev_page: lifeData.prev_page ? lifeData.prev_page : "",
  vuex_car_list: lifeData.vuex_car_list ? lifeData.vuex_car_list : [],
  vuex_user_code: lifeData.vuex_user_code ? lifeData.vuex_user_code : null
}

const mutations = {
  $uStore(state, payload) {
    let nameArr = payload.name.split('.');
    let saveKey = '';
    let len = nameArr.length;
    if (nameArr.length >= 2) {
      let obj = state[nameArr[0]];
      for (let i = 1; i < len - 1; i++) {
        obj = obj[nameArr[i]];
      }
      obj[nameArr[len - 1]] = payload.value;
      saveKey = nameArr[0];
    } else {
      state[payload.name] = payload.value;
      saveKey = payload.name;
    }
    // 保存变量到本地
    saveLifeData(saveKey, state[saveKey])
  }
}


const store = new Vuex.Store({
  state,
  mutations,
})

export default store